<template>
  <div class="page-container">
    <!-- 页面标题 -->
    <div class="flex justify-between items-center mb-6">
      <div>
        <h1 class="page-title">日志管理</h1>
        <div class="breadcrumb-container">
          <router-link to="/" class="link link-hover">首页</router-link>
          <span class="mx-2">/</span>
          <span>日志管理</span>
        </div>
      </div>
      <div class="btn-group">
        <button class="btn btn-error gap-2" @click="handleClear">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
            <path fill-rule="evenodd" d="M9 2a1 1 0 00-.894.553L7.382 4H4a1 1 0 000 2v10a2 2 0 002 2h8a2 2 0 002-2V6a1 1 0 100-2h-3.382l-.724-1.447A1 1 0 0011 2H9zM7 8a1 1 0 012 0v6a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v6a1 1 0 102 0V8a1 1 0 00-1-1z" clip-rule="evenodd" />
          </svg>
          清理日志
        </button>
        <button class="btn btn-primary gap-2" @click="handleExport">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
            <path fill-rule="evenodd" d="M3 17a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zm3.293-7.707a1 1 0 011.414 0L9 10.586V3a1 1 0 112 0v7.586l1.293-1.293a1 1 0 111.414 1.414l-3 3a1 1 0 01-1.414 0l-3-3a1 1 0 010-1.414z" clip-rule="evenodd" />
          </svg>
          导出日志
        </button>
      </div>
    </div>

    <!-- 搜索栏 -->
    <div class="card bg-base-100 shadow-lg mb-6">
      <div class="card-body">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div class="form-control">
            <label class="label">
              <span class="label-text">关键词</span>
            </label>
            <input
              v-model="searchForm.keyword"
              type="text"
              placeholder="请输入关键词"
              class="input input-bordered"
            />
          </div>
          <div class="form-control">
            <label class="label">
              <span class="label-text">日志类型</span>
            </label>
            <select v-model="searchForm.type" class="select select-bordered">
              <option value="">全部</option>
              <option value="info">信息</option>
              <option value="warning">警告</option>
              <option value="error">错误</option>
            </select>
          </div>
          <div class="form-control">
            <label class="label">
              <span class="label-text">模块</span>
            </label>
            <select v-model="searchForm.module" class="select select-bordered">
              <option value="">全部</option>
              <option value="user">用户管理</option>
              <option value="judgment">审判管理</option>
              <option value="hell">地狱管理</option>
              <option value="reincarnation">轮回管理</option>
              <option value="system">系统管理</option>
            </select>
          </div>
          <div class="form-control">
            <label class="label">
              <span class="label-text">时间范围</span>
            </label>
            <div class="join">
              <input
                v-model="searchForm.startTime"
                type="date"
                class="join-item input input-bordered w-[50%]"
              />
              <input
                v-model="searchForm.endTime"
                type="date"
                class="join-item input input-bordered w-[50%]"
              />
            </div>
          </div>
        </div>
        <div class="flex justify-end mt-4">
          <button class="btn btn-ghost" @click="resetSearch">重置</button>
          <button class="btn btn-primary ml-2" @click="handleSearch">搜索</button>
        </div>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="card bg-base-100 shadow-lg">
      <div class="card-body">
        <div class="overflow-x-auto">
          <table class="table">
            <thead>
              <tr>
                <th>时间</th>
                <th>类型</th>
                <th>模块</th>
                <th>操作人</th>
                <th>IP地址</th>
                <th>内容</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="log in logs" :key="log.id">
                <td>{{ formatDate(log.time) }}</td>
                <td>
                  <div class="badge" :class="getTypeBadgeClass(log.type)">
                    {{ getTypeLabel(log.type) }}
                  </div>
                </td>
                <td>{{ getModuleLabel(log.module) }}</td>
                <td>{{ log.operator }}</td>
                <td class="font-mono">{{ log.ip }}</td>
                <td class="max-w-md truncate">{{ log.content }}</td>
                <td>
                  <button class="btn btn-ghost btn-xs" @click="showDetails(log)">
                    详情
                  </button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- 分页 -->
        <div class="flex justify-between items-center mt-4">
          <div class="text-sm text-base-content/60">
            共 {{ total }} 条记录
          </div>
          <div class="join">
            <button class="join-item btn btn-sm" :disabled="currentPage === 1" @click="handlePageChange(currentPage - 1)">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
                <path fill-rule="evenodd" d="M12.707 5.293a1 1 0 010 1.414L9.414 10l3.293 3.293a1 1 0 01-1.414 1.414l-4-4a1 1 0 010-1.414l4-4a1 1 0 011.414 0z" clip-rule="evenodd" />
              </svg>
            </button>
            <button class="join-item btn btn-sm">{{ currentPage }} / {{ totalPages }}</button>
            <button class="join-item btn btn-sm" :disabled="currentPage === totalPages" @click="handlePageChange(currentPage + 1)">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
                <path fill-rule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clip-rule="evenodd" />
              </svg>
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 详情对话框 -->
    <dialog ref="detailsDialog" class="modal">
      <div class="modal-box">
        <h3 class="font-bold text-lg">日志详情</h3>
        <div class="py-4 space-y-4">
          <div class="grid grid-cols-2 gap-4">
            <div>
              <div class="text-sm text-base-content/60">时间</div>
              <div>{{ formatDate(selectedLog?.time) }}</div>
            </div>
            <div>
              <div class="text-sm text-base-content/60">类型</div>
              <div class="badge" :class="getTypeBadgeClass(selectedLog?.type)">
                {{ getTypeLabel(selectedLog?.type) }}
              </div>
            </div>
            <div>
              <div class="text-sm text-base-content/60">模块</div>
              <div>{{ getModuleLabel(selectedLog?.module) }}</div>
            </div>
            <div>
              <div class="text-sm text-base-content/60">操作人</div>
              <div>{{ selectedLog?.operator }}</div>
            </div>
            <div>
              <div class="text-sm text-base-content/60">IP地址</div>
              <div class="font-mono">{{ selectedLog?.ip }}</div>
            </div>
            <div>
              <div class="text-sm text-base-content/60">浏览器</div>
              <div>{{ selectedLog?.userAgent }}</div>
            </div>
          </div>
          <div>
            <div class="text-sm text-base-content/60">内容</div>
            <pre class="whitespace-pre-wrap mt-2 p-4 bg-base-200 rounded-lg">{{ selectedLog?.content }}</pre>
          </div>
        </div>
        <div class="modal-action">
          <button class="btn" @click="closeDetails">关闭</button>
        </div>
      </div>
      <form method="dialog" class="modal-backdrop">
        <button>关闭</button>
      </form>
    </dialog>

    <!-- 清理对话框 -->
    <dialog ref="clearDialog" class="modal">
      <div class="modal-box">
        <h3 class="font-bold text-lg">清理日志</h3>
        <div class="py-4">
          <div class="form-control">
            <label class="label">
              <span class="label-text">清理范围</span>
            </label>
            <select v-model="clearForm.range" class="select select-bordered">
              <option value="all">全部日志</option>
              <option value="date">指定日期前</option>
              <option value="type">指定类型</option>
            </select>
          </div>
          <div class="form-control mt-4" v-if="clearForm.range === 'date'">
            <label class="label">
              <span class="label-text">日期</span>
            </label>
            <input
              v-model="clearForm.date"
              type="date"
              class="input input-bordered"
            />
          </div>
          <div class="form-control mt-4" v-if="clearForm.range === 'type'">
            <label class="label">
              <span class="label-text">日志类型</span>
            </label>
            <select v-model="clearForm.type" class="select select-bordered">
              <option value="info">信息</option>
              <option value="warning">警告</option>
              <option value="error">错误</option>
            </select>
          </div>
        </div>
        <div class="modal-action">
          <button class="btn btn-ghost" @click="closeClear">取消</button>
          <button
            class="btn btn-error"
            :class="{ loading: isClearing }"
            @click="confirmClear"
          >
            确认清理
          </button>
        </div>
      </div>
      <form method="dialog" class="modal-backdrop">
        <button>关闭</button>
      </form>
    </dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { formatDate } from '@/utils/date'
import { LogService } from '@/api/services'
import { useLoadingStore } from '@/stores/loading'
import { useToast } from '@/composables/useToast'

const loadingStore = useLoadingStore()
const toast = useToast()

// 搜索表单
interface SearchForm {
  keyword: string
  type: string
  module: string
  startTime: string
  endTime: string
}

const searchForm = reactive<SearchForm>({
  keyword: '',
  type: '',
  module: '',
  startTime: '',
  endTime: '',
})

// 清理表单
interface ClearForm {
  range: 'all' | 'date' | 'type'
  date: string
  type: string
}

const clearForm = reactive<ClearForm>({
  range: 'all',
  date: '',
  type: 'info',
})

// 状态
const logs = ref([
  {
    id: 1,
    time: '2024-01-15T12:00:00Z',
    type: 'info',
    module: 'user',
    operator: '判官王',
    ip: '192.168.1.1',
    content: '用户登录成功',
    userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
  },
  {
    id: 2,
    time: '2024-01-15T11:30:00Z',
    type: 'warning',
    module: 'judgment',
    operator: '黑无常',
    ip: '192.168.1.2',
    content: '审判记录更新失败：数据验证错误',
    userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
  },
  {
    id: 3,
    time: '2024-01-15T11:00:00Z',
    type: 'error',
    module: 'system',
    operator: '白无常',
    ip: '192.168.1.3',
    content: '系统异常：数据库连接失败\nError: Connection refused',
    userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
  },
])

const currentPage = ref(1)
const total = ref(100)
const totalPages = computed(() => Math.ceil(total.value / 10))

const detailsDialog = ref<HTMLDialogElement | null>(null)
const clearDialog = ref<HTMLDialogElement | null>(null)
const selectedLog = ref(null)
const isClearing = ref(false)

// 方法
const getTypeBadgeClass = (type: string) => {
  switch (type) {
    case 'info':
      return 'badge-info'
    case 'warning':
      return 'badge-warning'
    case 'error':
      return 'badge-error'
    default:
      return 'badge-ghost'
  }
}

const getTypeLabel = (type: string) => {
  switch (type) {
    case 'info':
      return '信息'
    case 'warning':
      return '警告'
    case 'error':
      return '错误'
    default:
      return '未知'
  }
}

const getModuleLabel = (module: string) => {
  switch (module) {
    case 'user':
      return '用户管理'
    case 'judgment':
      return '审判管理'
    case 'hell':
      return '地狱管理'
    case 'reincarnation':
      return '轮回管理'
    case 'system':
      return '系统管理'
    default:
      return '未知'
  }
}

const handleSearch = async () => {
  try {
    loadingStore.show()
    const { items, total: totalCount } = await LogService.getLogs({
      page: currentPage.value,
      pageSize: 10,
      ...searchForm,
    })
    logs.value = items
    total.value = totalCount
  } catch (error: any) {
    toast.error(error.message)
  } finally {
    loadingStore.hide()
  }
}

const resetSearch = () => {
  searchForm.keyword = ''
  searchForm.type = ''
  searchForm.module = ''
  searchForm.startTime = ''
  searchForm.endTime = ''
  handleSearch()
}

const handlePageChange = (page: number) => {
  currentPage.value = page
  handleSearch()
}

const handleExport = async () => {
  try {
    loadingStore.show()
    await LogService.exportLogs(searchForm)
    toast.success('导出成功')
  } catch (error: any) {
    toast.error(error.message)
  } finally {
    loadingStore.hide()
  }
}

const handleClear = () => {
  clearDialog.value?.showModal()
}

const confirmClear = async () => {
  try {
    isClearing.value = true
    await LogService.clearLogs(clearForm)
    toast.success('清理成功')
    closeClear()
    handleSearch()
  } catch (error: any) {
    toast.error(error.message)
  } finally {
    isClearing.value = false
  }
}

const showDetails = (log: any) => {
  selectedLog.value = log
  detailsDialog.value?.showModal()
}

const closeDetails = () => {
  detailsDialog.value?.close()
}

const closeClear = () => {
  clearDialog.value?.close()
}

// 初始加载
handleSearch()
</script>
